package com.springboot.activiti.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.VariableInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springboot.activiti.dto.ProcessButton;
import com.springboot.activiti.dto.WorkflowDTO;
import com.springboot.activiti.model.UserModel;
import com.springboot.activiti.service.UserService;
import com.springboot.activiti.service.WorkflowService;
import com.springboot.activiti.vo.HistoryTaskVO;
import com.springboot.activiti.vo.TaskVO;

@Controller
@RequestMapping({"/workflow"})
public class WorkflowController {
	
	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private WorkflowService workflowService;
	
	@Autowired
	private HistoryService historyService;
	
	@RequestMapping("/myTask")
	public String myTask(HttpSession session, Model model){
		List<TaskVO> tasks = new ArrayList<TaskVO>();
		
		String userId = (String) session.getAttribute("loginUser");
		List<Task> list = taskService.createTaskQuery().taskCandidateOrAssigned(userId).list();
		for(Task task : list){
			TaskVO taskVO = new TaskVO();
			
			String processTitle = (String) runtimeService.getVariable(task.getExecutionId(), "processTitle");
			String name = task.getName();
			Date createTime = task.getCreateTime();
			VariableInstance variableInstance = runtimeService.getVariableInstance(task.getExecutionId(), "applyUserId");
			UserModel userModel = userService.selectById(variableInstance.getValue().toString());
			String initiator = userModel.getName();
			//ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
			
			taskVO.setTaskId(task.getId());
			taskVO.setProcessTitle(processTitle);
			taskVO.setName(name);
			taskVO.setCreateTime(createTime);
			taskVO.setInitiator(initiator);
			taskVO.setNeedClaim(task.getAssignee()==null?true:false);
			taskVO.setFormUrl(task.getFormKey());
			//Map<String, Object> map = processInstance.getProcessVariables();
			//String businessKey = processInstance.getBusinessKey();
			
			tasks.add(taskVO);
		}
		model.addAttribute("tasks", tasks);
		return "workflow/list";
	}
	
	/** 查看历史的批注信息*/
	@RequestMapping("/viewHisComment")
	public String viewHisComment(Model model, String taskId){
		List<Comment> commentList = workflowService.findCommentByTaskId(taskId);
		model.addAttribute("commentList", commentList);
		return "workflow/processHistroy";
	}
	
	
	/**
	 * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
	 */
	@RequestMapping("/processTask")
	public String processTask(Model model, String taskId, String formUrl, boolean needClaim){
		model.addAttribute("taskId", taskId);
		model.addAttribute("formUrl", formUrl);
		
		//如果需要认领任务，则先认领
		if(needClaim){
			taskService.claim(taskId, "3");//3,为当前登录人的ID
		}
		
		List<ProcessButton> processButtons = (List<ProcessButton>) taskService.getVariableLocal(taskId, "processButtons");
		model.addAttribute("processButtons", processButtons);
		
		return "workflow/processTask";
	}
	
	/**
	 * 完成任务
	 */
	@RequestMapping("/completeTask")
	public String completeTask(Model model, String taskId, String outcome,String message, HttpSession session){
		String userId = (String) session.getAttribute("loginUser");
		
		model.addAttribute("taskId", taskId);
		workflowService.completeTask(taskId, outcome, userId, message);
		return "forward:myTask";
	}
	
	
	/**
	 * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
	 */
	@RequestMapping("/viewProcessImage")
	public String viewProcessImage(Model model, String taskId){
		/**一：查看流程图*/
		//1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
		ProcessDefinition processDefinition = workflowService.findProcessDefinitionByTaskId(taskId);
		//workflowAction_viewImage?deploymentId=<s:property value='#deploymentId'/>&imageName=<s:property value='#imageName'/>
		model.addAttribute("deploymentId", processDefinition.getDeploymentId());
		model.addAttribute("imageName", processDefinition.getDiagramResourceName());
		/**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
		Map<String, Object> map = workflowService.findCoordingByTask(taskId);
		model.addAttribute("acs", map);
		return "workflow/image";
	}
	
	/**
	 * 查看流程图
	 * @throws Exception 
	 */
	@RequestMapping("/viewImage")
	public String viewImage(WorkflowDTO workflowDTO, HttpServletResponse response) throws Exception{
		//1：获取页面传递的部署对象ID和资源图片名称
		//部署对象ID
		String deploymentId = workflowDTO.getDeploymentId();
		//资源图片名称
		String imageName = workflowDTO.getImageName();
		//2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
		InputStream in = workflowService.findImageInputStream(deploymentId, imageName);
		//3：从response对象获取输出流
		OutputStream out = response.getOutputStream();
		//4：将输入流中的数据读取出来，写到输出流中
		for(int b=-1;(b=in.read())!=-1;){
			out.write(b);
		}
		out.close();
		in.close();
		//将图写到页面上，用输出流写
		return null;
	}
	
	//我的已办
	@RequestMapping("/myDoneTask")
	public String myDoneTask(HttpSession session, Model model){
		List<HistoryTaskVO> tasks = new ArrayList<HistoryTaskVO>();
		
		String userId = (String) session.getAttribute("loginUser");
		List<HistoricActivityInstance> hisList = historyService.createHistoricActivityInstanceQuery().taskAssignee(userId).list();
		for(HistoricActivityInstance task : hisList){
			HistoryTaskVO historyTaskVO = new HistoryTaskVO();
			
			String processTitle = (String) runtimeService.getVariable(task.getExecutionId(), "processTitle");
			String name = task.getActivityName();
			
			
			Date startTime = task.getStartTime();
			Date endTime = task.getEndTime();
			
			VariableInstance variableInstance = runtimeService.getVariableInstance(task.getExecutionId(), "applyUserId");
			UserModel userModel = userService.selectById(variableInstance.getValue().toString());
			String initiator = userModel.getName();
			//ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
			String processInstanceId = task.getProcessInstanceId();
			
			HistoricVariableInstance hv = historyService.createHistoricVariableInstanceQuery().taskId(task.getTaskId()).variableName("outcome").singleResult();
			String outcome = (String) hv.getValue();
			
			historyTaskVO.setTaskId(task.getTaskId());
			historyTaskVO.setProcessTitle(processTitle);
			historyTaskVO.setName(name);
			historyTaskVO.setStartTime(startTime);
			historyTaskVO.setEndTime(endTime);
			historyTaskVO.setInitiator(initiator);
			//durationTime 持续时长需要计算
			historyTaskVO.setProcessInstanceId(processInstanceId);
			
			tasks.add(historyTaskVO);
		}
		model.addAttribute("tasks", tasks);
		return "workflow/list";
	}
	
	
}
